package com.acme.bankapp.service.bank.impl;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

import com.acme.bankapp.domine.account.Account;
import com.acme.bankapp.domine.bank.Bank;
import com.acme.bankapp.domine.bank.ClientRegistrationListener;
import com.acme.bankapp.domine.client.Client;
import com.acme.bankapp.domine.client.Gender;
import com.acme.bankapp.exceptions.ClientExistsException;
import com.acme.bankapp.service.bank.BankService;

public class BankServiceImpl implements BankService {

    @Override
    public Bank createNewBank() {
        return new Bank();
    }

    @Override
    public Bank createNewBank(final List<ClientRegistrationListener>
            clientRegistrationListenerList) {
        return new Bank(clientRegistrationListenerList);
    }

    @Override
    public void addClient(final Bank bank, final Client client)
            throws ClientExistsException {
        bank.addClient(client);
    }

    @Override
    public Client addClient(final Bank bank, final String name,
            final Gender gender) throws ClientExistsException {
        Client client = new Client(name, gender);
        bank.addClient(client);
        return client;
    }

    @Override
    public void printBalance(final Bank bank) {
        System.out.println("printBalance");
        for (Client client: bank.getClients()) {
            System.out.println(client);
        }
    }

    @Override
    public void printMaximumAmountToWithdraw(final Bank bank) {
        System.out.println("printMaximumAmountToWithdraw");
        for (Client client: bank.getClients()) {
            for (Account account: client.getAccounts()) {
                System.out.println(client.getClientSalutation() + " : "
                        + account + " : " + account.maximumAmountToWithdraw());
            }
        }
    }

    @Override
    public void saveBank(final Bank bank, final String pathTo) throws IOException {
        FileOutputStream fos = new FileOutputStream(pathTo);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(bank);
        oos.close();
        fos.close();
    }

    @Override
    public Bank loadBank(final String pathFrom) throws IOException {
        Bank bank;
        FileInputStream fos = new FileInputStream(pathFrom);
        ObjectInputStream oos = new ObjectInputStream(fos);
        try {
            bank = (Bank) oos.readObject();
        } catch (ClassNotFoundException e) {
            bank = new Bank();
        }
        oos.close();
        fos.close();
        return bank;
    }
}
